import {AvatarDropdown, AvatarName, Footer, Question} from '@/components';
import {currentUser} from '@/services/ant-design-pro/api';
import {LinkOutlined} from '@ant-design/icons';
import type {Settings as LayoutSettings} from '@ant-design/pro-components';
import {SettingDrawer} from '@ant-design/pro-components';
import {RequestConfig, RunTimeLayoutConfig} from '@umijs/max';
import {history, Link} from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import {errorConfig} from './requestErrorConfig';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const WHITE_LIST = ['/user/register', loginPath];

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async (): Promise<API.CurrentUser | undefined> => {
    try {
      console.log('开始获取用户信息...');

      // 调用API获取当前用户信息
      const response = await currentUser({
        skipErrorHandler: true,
      });

      console.log('获取用户信息响应:', response);

      // 类型安全的检查：确保response存在且是对象
      if (!response || typeof response !== 'object') {
        console.log('返回数据无效');
        return undefined;
      }

      // 检查是否是统一返回格式 BaseResponse<CurrentUser>
      if ('code' in response && 'message' in response) {
        const baseResponse = response as API.CurrentUserResult;
        if (baseResponse.code === 0 && baseResponse.data) {
          console.log('用户信息获取成功:', baseResponse.data);
          return baseResponse.data;
        } else {
          console.log('用户信息获取失败:', {
            code: baseResponse.code,
            message: baseResponse.message,
            description: baseResponse.description
          });

          // 如果是未登录相关的错误码，不需要报错，正常返回 undefined
          if (baseResponse.code === 40100 || baseResponse.code === 401) {
            console.log('用户未登录或登录已过期');
          } else {
            console.error('获取用户信息业务错误:', baseResponse.message);
          }

          return undefined;
        }
      }

      // 兼容旧格式：如果直接返回用户对象（向后兼容）
      else if ('id' in response && 'username' in response) {
        console.log('兼容模式：直接返回用户信息');
        return response as API.CurrentUser;
      }

      console.log('返回数据格式异常:', response);
      return undefined;

    } catch (error: any) {
      console.log('获取用户信息请求异常:', error);

      // 如果是网络错误或401错误，不显示错误信息，静默处理
      if (error?.response?.status === 401 || error?.response?.status === 403) {
        console.log('认证失败，用户需要重新登录');
      } else if (error?.code === 'NETWORK_ERROR' || error?.message?.includes('timeout')) {
        console.log('网络请求失败:', error.message);
      } else {
        console.error('未知错误:', error);
      }

      return undefined;
    }
  };

  // 获取当前路径
  const {location} = history;
  console.log('当前路径:', location.pathname);
  console.log('白名单:', WHITE_LIST);

  // 如果不是白名单页面，需要验证登录状态
  if (!WHITE_LIST.includes(location.pathname)) {
    console.log('当前页面不在白名单中，开始验证登录状态...');
    const currentUser = await fetchUserInfo();

    if (!currentUser) {
      console.log('用户未登录或登录已过期，跳转到登录页');

      // 保存当前路径，登录成功后可以跳转回来
      const currentPath = location.pathname + location.search;
      const redirectPath = currentPath !== loginPath ? `${loginPath}?redirect=${encodeURIComponent(currentPath)}` : loginPath;

      history.push(redirectPath);

      return {
        fetchUserInfo,
        settings: defaultSettings as Partial<LayoutSettings>,
      };
    }

    console.log('用户已登录，初始化完成');
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }

  console.log('当前页面在白名单中，跳过登录验证');
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {
  return {
    actionsRender: () => [<Question key="doc"/>],
    avatarProps: {
      src: initialState?.currentUser?.avatarUrl,
      title: <AvatarName/>,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.username,
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: isDev
      ? [
        <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined/>
          <span>OpenAPI 文档</span>
        </Link>,
      ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // 添加运行时登录状态检查
      const {location} = history;

      // 如果不是白名单页面且没有用户信息，跳转到登录页
      if (!WHITE_LIST.includes(location.pathname) && !initialState?.currentUser) {
        console.log('运行时检查：用户未登录，跳转到登录页');

        // 保存当前路径用于登录后跳转
        const currentPath = location.pathname + location.search;
        const redirectPath = currentPath !== loginPath ? `${loginPath}?redirect=${encodeURIComponent(currentPath)}` : loginPath;

        history.push(redirectPath);
        return <div style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh'
        }}>跳转中...</div>;
      }

      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request: RequestConfig = {
  ...errorConfig,
  timeout: 10000,
};
